<?php

namespace Common\Model;

/**
 * 关注，逻辑是user_id 关注了 to_user_id
 */
class FollowModel extends BaseModel
{
    protected $_auto = [
        ['created_at', 'time', self::MODEL_INSERT, 'function'],
    ];

    protected $_validate = [
        ['user_id', 'require', '关注人的ID不能为空'],
        ['to_user_id', 'require', '关注对象的ID不能为空'],
    ];

    protected $_scope = [
    ];


    public function addFollow($from, $to)
    {
        $follow = D('Follow')->where(['user_id' => $from, 'to_user_id' => $to])->find();
        if ($follow) {
            throw new ModelException(40001);
        } elseif ($from == $to) {
            throw new ModelException(40003);
        }
        $data = [
            'user_id' => $from,
            'to_user_id' => $to,
        ];
        
        $followModel = D('Follow');
        if ($followModel->create($data)) {
            $followModel->add();
            /* 关注数+1 */
            D('Users')->where(['id' => $from])->setInc('like_num', 1);
            /* 粉丝数+1 */
            D('Users')->where(['id' => $to])->setInc('fans_num', 1);
            return true;
        } else {
            throw new ModelException(40002, $followModel->getError());
        }
        
    }

    public function delFans($from, $to)
    {
        $isExist = D('Fans')->where(['user_id' => $from, 'to_user_id' => $to])->find();
        if ($isExist) {
            D('Fans')->where(['user_id' => $from, 'to_user_id' => $to])->delete();
            /* 粉丝数-1 */
            D('Users')->where(['id' => $to])->setDec('fans_num', 1);
            D('Users')->where(['id' => $from])->setDec('like_num', 1);
            return true;
        } else {
            $this->error = '未关注该用户';
            $this->errorCode = 40002;
            return false;
        }
    }

    


}
